package io.github.talelin.latticy.controller.v1;


import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.core.annotation.GroupRequired;
import io.github.talelin.core.annotation.PermissionMeta;
import io.github.talelin.latticy.dto.machine.CreateOrUpdateMachineDTO;
import io.github.talelin.latticy.model.MachineDO;
import io.github.talelin.latticy.service.MachineService;
import io.github.talelin.latticy.vo.CreatedVO;
import io.github.talelin.latticy.vo.DeletedVO;
import io.github.talelin.latticy.vo.UpdatedVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Positive;
import java.util.List;

/**
* @author generator@TaleLin
* @since 2021-05-20
*/
@RestController
@RequestMapping("/v1/machine")
public class MachineController {

    @Autowired
    MachineService machineService;


    @PostMapping("")
    public CreatedVO createBook(@RequestBody @Validated CreateOrUpdateMachineDTO validator) {
        System.out.println(validator);
        machineService.createMachine(validator);
        return new CreatedVO(19);
    }

    @GetMapping("/{id}")
    public MachineDO getMachine(@PathVariable(value = "id") @Positive(message = "{id.positive}") Integer id) {
        MachineDO machine = machineService.getById(id);
        if (machine == null) {
            throw new NotFoundException(10022);
        }
        return machine;
    }

    @PutMapping("/{id}")
    public UpdatedVO updateMachine(@PathVariable("id") @Positive(message = "{id.positive}") Integer id, @RequestBody @Validated CreateOrUpdateMachineDTO validator) {

        MachineDO machine = machineService.getById(id);
        if (machine == null) {
            throw new NotFoundException(10022);
        }
        machineService.updateMachine(machine, validator);
        return new UpdatedVO(13);
    }
    @GetMapping("")
    @GroupRequired
    @PermissionMeta(value = "查看所有机器", module = "机器")
    public List<MachineDO> getMachine() {
        List<MachineDO> machine = machineService.findAll();
        return machine;
    }

    @DeleteMapping("/{id}")
    @GroupRequired
    @PermissionMeta(value = "删除机器", module = "机器")
    public DeletedVO deleteMachine(@PathVariable("id") @Positive(message = "{id.positive}") Integer id) {
        MachineDO machine = machineService.getById(id);
        if (machine == null) {
            throw new NotFoundException(10022);
        }
        machineService.deleteById(machine.getId());
        return new DeletedVO(3);
    }

}
